<template>
    <div class="container">

        <div class="body_wrap">

            <el-card shadow="hover" ref="content_card">

                <!-- 基本搜索+功能按钮 -->
                <el-form ref="search" :inline="true" :model="queryParams" size="medium" label-width="">
                    <el-card class="table_tool_bar_wrap" shadow="never">
                        <div class="base_wrap">
                            <div class="left">
                                <el-form-item label="" prop="keyword">
                                    <el-input placeholder="请输入：登录账号/姓名" v-model="queryParams.keyword" clearable/>
                                </el-form-item>
                                <el-form-item label="状态" prop="status">
                                    <el-select placeholder="" v-model="queryParams.status" clearable>
                                        <el-option label="正常" value="0"></el-option>
                                        <el-option label="禁用" value="1"></el-option>
                                    </el-select>
                                </el-form-item>

                                <el-button @click="handleSearch" type="primary" size="medium">搜索</el-button>
                                <el-button @click="handleReset" type="info" plain size="medium">重置</el-button>
                            </div>

                            <div class="right">
                                <el-button v-if="isAuth('system:user:add')" @click="handleAddOrUpdateVisible()" type="primary" size="medium" icon="el-icon-plus">新增</el-button>
                                <el-button v-if="isAuth('system:user:delete')" @click="handleDelete()" type="danger" size="medium" icon="el-icon-delete" :disabled="selectionRows.length == 0" >删除</el-button>
                                <el-dropdown class="ml10" @command="handleCommand">
                                    <el-button type="primary" size="medium">
                                        更多操作<i class="el-icon-arrow-down el-icon--right"></i>
                                    </el-button>
                                    <el-dropdown-menu slot="dropdown">
                                        <el-dropdown-item command="broadcast-message">广播消息</el-dropdown-item>
                                        <el-dropdown-item command="reset-password">重置密码</el-dropdown-item>
                                        <el-dropdown-item command="export-data">导出信息</el-dropdown-item>
                                    </el-dropdown-menu>
                                </el-dropdown>
                            </div>
                        </div>
                    </el-card>
                </el-form>

                <!-- 表格 -->
                <el-table
                    ref="table"
                    size="medium"
                    height="650"
                    empty-text="暂无数据"
                    element-loading-text="给我一点时间"
                    fit border highlight-current-row
                    :stripe="stripe"
                    v-loading="loading"
                    :data="dataList"
                    @selection-change="handleSelection">

                    <el-table-column type="selection" width="55" prop="selection" align="center"></el-table-column>
                    <el-table-column label="序号" type="index" prop="index" width="60" align="center" />
                    <el-table-column label="头像" prop="avatar" align="center" width="100">
                        <template slot-scope="scope">
                            <div style="display:flex;justify-content: center;">
                                <el-avatar :size="30" :src="scope.row.avatar">
                                    <img src="https://dev-file.iviewui.com/userinfosvaY5tb7yfnSFTTimcjy3vuSG6RC28v2/avatar"/>
                                </el-avatar>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="用户名" prop="username" width="150px" align="left" show-overflow-tooltip/>
                    <el-table-column label="姓名" prop="realname" width="150px" align="left" show-overflow-tooltip/>
                    <el-table-column label="手机" prop="mobile" width="150px" align="left" show-overflow-tooltip/>
                    <el-table-column label="邮箱" prop="email" align="left" width="300px" show-overflow-tooltip/>
                    <el-table-column label="性别" prop="sex" align="center" width="80px">
                        <template slot-scope="scope">
                            <el-tag type="primary" size="small" v-if="scope.row.sex === '1'">男</el-tag>
                            <el-tag type="success" size="small" v-else-if="scope.row.sex === '2'">女</el-tag>
                            <el-tag type="danger" size="small" v-else>保密</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="角色" prop="roles" align="left">
                        <template slot-scope="scope">
                            <template v-if="scope.row.roles">
                                <el-tooltip placement="top">
                                    <div slot="content">
                                        <div class="tipView" v-for="(item, index) in scope.row.roles" :key="index">
                                            {{item}}
                                        </div>
                                    </div>
                                    <div>
                                        {{scope.row.roles[0]}}
                                        <i v-if="scope.row.roles.length > 1" class="el-icon-more" style="color: #F56C6C"></i>
                                    </div>
                                </el-tooltip>
                            </template>
                        </template>
                    </el-table-column>
                    <el-table-column label="状态" prop="status" align="center" width="100px">
                        <template slot-scope="scope">
                            <el-switch
                                v-model="scope.row.status"
                                active-color="#13ce66"
                                inactive-color="#ff4949"
                                :active-value="0"
                                :inactive-value="1"
                                @change="handleChangeStatus(scope.row)">
                            </el-switch>
                        </template>
                    </el-table-column>
                    <el-table-column label="创建时间" prop="ctime" align="left" width="160" show-overflow-tooltip/>

                    <el-table-column label="操作" prop="btn" width="200px" align="left" fixed="right">
                        <template slot-scope="scope">
                            <el-button v-if="isAuth('system:user:update')" @click="handleAddOrUpdateVisible(scope.row.id)" type="text" size="small">编辑</el-button>
                            <el-button @click="handleDelete(scope.row)" v-if="scope.row.username !== 'admin'" type="text" size="small">删除</el-button>
                            <el-button @click="handleDrawerVisible(scope.row.id)" type="text" size="small">详情</el-button>
                        </template>
                    </el-table-column>

                </el-table>

                <!-- 分页 -->
                <TablePagination
                    :total.sync="queryParams.total"
                    :page.sync="queryParams.page"
                    :limit.sync="queryParams.limit"
                    @handleSizeChange="handleSizeChange"
                    @handleCurrentChange="handleCurrentChange"/>
            </el-card>

            <!-- 弹窗, 新增 / 修改 -->
            <AddOrUpdate ref="addOrUpdate" @refreshDataList="getDataList"></AddOrUpdate>

            <!-- 右侧抽屉,详情信息 -->
            <el-drawer
                ref="drawer"
                class="drawer_wrap"
                size="1000px"
                :visible.sync="drawerVisible"
                :with-header="false"
                :modal="true"
                direction="rtl"
                :before-close="handleCloseDrawerDetail">
                <div class="header_title">
                    <div class="title"><i class="el-icon-document"></i> 详情</div>
                    <div class="close el-icon-close" @click="$refs.drawer.closeDrawer()"></div>
                </div>

                <div class="header_body">
                    <el-form :model="detail" :inline="true" label-width="120">
                        <el-row>
                            <el-col :span="24" style="display: flex; justify-content: center;margin-bottom: 20px;">
                                <el-avatar :size="150" :src="detail.avatar">
                                    <img src="https://dev-file.iviewui.com/userinfosvaY5tb7yfnSFTTimcjy3vuSG6RC28v2/avatar"/>
                                </el-avatar>
                            </el-col>
                        </el-row>
                        <table class="detail_wrap">
                            <tbody>
                                <tr>
                                    <td class="title">用户名</td>
                                    <td class="info">{{detail.username}}</td>
                                    <td class="title">姓名</td>
                                    <td class="info">{{detail.realname}}</td>
                                </tr>
                                <tr>
                                    <td class="title">手机</td>
                                    <td class="info">{{detail.mobile}}</td>
                                    <td class="title">邮箱</td>
                                    <td class="info">{{detail.email}}</td>
                                </tr>
                                <tr>
                                    <td class="title">性别</td>
                                    <td class="info">
                                        <el-tag type="primary" size="small" v-if="detail.sex === 1">男</el-tag>
                                        <el-tag type="danger" size="small" v-else-if="detail.sex === 2">女</el-tag>
                                        <el-tag type="danger" size="small" v-else>保密</el-tag>
                                    </td>
                                    <td class="title">生日</td>
                                    <td class="info">{{detail.birthday}}</td>
                                </tr>
                                <tr>
                                    <td class="title">状态</td>
                                    <td class="info">
                                        <el-tag type="primary" size="small" v-if="detail.status === 0">正常</el-tag>
                                        <el-tag type="danger" size="small" v-else-if="detail.status === 1">禁用</el-tag>
                                    </td>
                                </tr>

                            </tbody>
                        </table>
                    </el-form>
                </div>
            </el-drawer>

            <el-dialog :title="selectionRows.length > 0 ? '用户消息' : '广播消息'" :close-on-click-modal="false" :visible.sync="dialogMessageVisible" @close="handleDialogCloseMessage">
                <el-tag v-for="item in selectionRows" :key="item.id" closable @close="handleClose(item)" style="margin-right: 10px;margin-bottom: 10px">
                    {{item.realname}}
                </el-tag>
                <el-form ref="message" :model="message" :rules="rulesMessage" >
                    <el-form-item prop="message">
                        <el-input type="textarea" :autosize="{ minRows: 6, maxRows: 1}" placeholder="请输入内容" v-model="message.text"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogMessageVisible=false">取 消</el-button>
                    <el-button type="primary" @click="handleSendMessage">确 定</el-button>
                </div>
            </el-dialog>

        </div>
    </div>
</template>

<script>

import { isAuth } from '@/libs/auth'
import TablePagination from '@/views/components/table/table-pagination'
import AddOrUpdate from './add-or-update-dialog'
import { mapGetters } from 'vuex'
export default {
    components: {
        TablePagination,
        AddOrUpdate
    },

    computed: {
        ...mapGetters(['user'])
    },

    data() {
        return {
            stripe: false,              // 隔行变色
            toggleSearchStatus: false,  // 查询折叠
            loading: false,             // 加载
            drawerVisible: false,       // 侧边栏详情
            selectionRows: [],          // 多选
            dataList: [],               // 数据列表

            queryParams: {
                total: 0,
                page: 1,
                limit: 10,
                order: 'username',
                asc: false,
                keyword: null,

                realname: null,
                username: null,
                password: null,
                salt: null,
                mobile: null,
                email: null,
                avatar: null,
                sex: null,
                birthday: null,
                status: null,
                superAdmin: null,
                ctime: null,
                utime: null
            },
            detail: {
                id: null,
                realname: null,
                username: null,
                password: null,
                salt: null,
                mobile: null,
                email: null,
                avatar: null,
                sex: null,
                birthday: null,
                status: null,
                superAdmin: null,
                ctime: null,
                utime: null
            },

            dialogMessageVisible: false,
            message: {
                from: null,
                // to: [],
                text: null
            },
            rulesMessage: {
                text: [
                    { required: true, message: '内容不能为空', trigger: 'blur' }
                ]
            },
        }
    },

    created() {
    },

    mounted() {
        this.$nextTick(() => {
            this.getDataList()
        })
    },

    methods: {

        /**
         * 侧边栏抽屉打开
         */
        handleDrawerVisible(id) {
            this.getInfo(id)
            this.drawerVisible = true
        },

        /**
         * 新增或编辑
         */
        handleAddOrUpdateVisible(id) {
            // 表单窗口
            this.$nextTick(() => {
                this.$refs.addOrUpdate.init(id)
            })
        },

        /**
         * 删除
         */
        async handleDelete(row) {
            let ids = []
            if (row) {
                ids.push(row.id)
            }
            if(this.selectionRows) {
                this.selectionRows.filter((item, index) => {
                    ids.push(item.id)
                })
            }
            if (ids.length <= 0) {
                this.$notify({ title: '提示', message: '请选择需要删除的记录！', type: 'info' });
            } else {
                const confirm = await this.$confirm('确定要删除？', '提示', { type: 'warning' }).catch(() => {})
                if(confirm) {
                    const res = await this.$http({
                        url: '/system/user/delete',
                        method: 'POST',
                        data: ids
                    })
                    if (this.ResultMessage(res)) {
                        this.getDataList()
                    }
                }
            }
        },

        /**
         * 详细信息
         */
         async getInfo(id) {
            if (id) {
                const res = await this.$http({
                    url: '/system/user/info/' + id,
                    method: 'GET'
                })
                this.detail = Object.assign({}, res.data)
            }
        },

        /**
         * 获取表格数据
         */
        async getDataList() {
            this.loading = true
            const res = await this.$http({
                url: '/system/user/page',
                method: 'GET',
                params: this.queryParams
            })
            if (this.ResultMessage(res, false)) {
                this.dataList = res.data.records || []

                this.dataList.forEach((item, index) => {
                    if(item.roles) {
                        let roles = []
                        item.roles.forEach((k, i) => {
                            roles.push(k.name)
                        })
                        item.roles = roles
                    }
                })

                this.queryParams.total = res.data.total
            }
            this.loading = false
        },

        /**
         * 修改状态
         */
        async handleChangeStatus(row) {
            this.loading = true
            await this.$http({
                url: '/system/user/changeStatus/'+row.id+'/'+row.status,
                method: 'GET'
            })
            this.loading = false
        },

        async handleCommand(command) {
            if (command === "reset-password") {
                // 重置密码
                this.handleResetPassword()
            } else if (command === "broadcast-message") {
                // 广播消息
                this.dialogMessageVisible = true
            } else if (command === "export-data") {
                this.handleExport()
            }
        },

        /**
         * 下载导出数据
         */
        async handleExport() {
            const notify = this.$notify({ title: '提示', message: '正在下载，请稍等。', type: 'success', duration: 0 });
            const data = await this.$http({
                url: '/system/user/export',
                method: 'POST',
                responseType: 'blob',
                data: {},
            }).catch(err => {console.log(err)})

            if (!data) { return }
            let url = window.URL.createObjectURL(new Blob([data]));
            let link = document.createElement('a');
            link.style.display = 'none';
            link.href = url;
            link.setAttribute('download', data.filename);

            document.body.appendChild(link);
            link.click()
            setTimeout(() => { notify.close() }, 1000)
        },

        /**
         * 重置密码
         */
        async handleResetPassword(row) {
            let ids = []
            if(this.selectionRows) {
                this.selectionRows.filter((item, index) => {
                    if (item.username !== 'admin') {
                        ids.push(item.id)
                    }
                })
            }
            if (ids.length <= 0) {
                this.$notify({ title: '提示', message: '请选项需要重置用户登陆密码的记录！', type: 'info' });
            } else {
                const confirm = await this.$confirm('密码将重置为【123456】', '提示', { type: 'warning' }).catch(() => {})
                if(confirm) {
                    const res = await this.$http({
                        url: '/system/user/batchResetPassword',
                        method: 'POST',
                        data: ids
                    })
                    if (this.ResultMessage(res)) {
                        this.getDataList()
                    }
                }
            }
        },

        /**
         * 发送即时消息
         */
        handleSendMessage() {
            let ids = []
            if(this.selectionRows) {
                this.selectionRows.filter((item, index) => {
                    ids.push(item.id)
                })
                this.message.from = this.user.id
                this.message.fromName = this.user.username
                this.message.to = ids
            }

            this.$http({
                url: `/websocket${ids.length > 0 ? '/sendMessageToUser' : '/sendSystemBroadcastMessage'}`,
                method: 'POST',
                data: this.message
            }).then(res => {
                if (this.ResultMessage(res)) {
                }
            })
        },

        handleDialogCloseMessage() {
            this.message = { from: null, to: [], text: null }
            this.$refs.table.clearSelection()
        },

        handleClose(item) {
            this.selectionRows.splice(this.selectionRows.indexOf(item), 1);
            this.$refs.table.toggleRowSelection(item, false)
        },

        /**
         * 每页数
         */
         handleSizeChange(val) {
            this.queryParams.limit = val
            this.getDataList()
        },

        /**
         * 当前页
         */
        handleCurrentChange(val) {
            this.queryParams.page = val
            this.getDataList()
        },

        /**
         * 多选
         */
        handleSelection(selection) {
            this.selectionRows = selection
        },

        /**
         * 搜索
         */
        handleSearch() {
            this.getDataList()
        },

        /**
         * 重置搜索表单
         */
        handleReset() {
            this.queryParams.page = 1
            this.queryParams.total = null
            this.$refs.search.resetFields()
            this.handleReload()
        },

        /**
         * 重新加载数据表格
         */
        handleReload() {
            this.getDataList()
        },

        /**
         * 侧边栏抽屉关闭
         */
        handleCloseDrawerDetail(done) {
            done();
        }

    }

}
</script>

<style lang="scss" scoped>
.tipView{
    padding: 5px;
}
</style>
